package br.edu.ufersa.scrumgame.mbean.converter;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import br.edu.ufersa.scrumgame.facade.PapelFacade;
import br.edu.ufersa.scrumgame.modelo.Papel;

@FacesConverter(value = "papelConverter")
@ManagedBean
public class PapelConverter implements Converter {

	@EJB
	private PapelFacade papelFacade;

	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {

		if (submittedValue == null || submittedValue.length() == 0) {
			return null;
		}

		try {
			Papel papel = papelFacade.findByDescricao(submittedValue);
			return papel;
		} catch (NumberFormatException e) {
			throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not valid"));
		}
	}

	@Override
	public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
		String retorno = "";

		if (value instanceof Papel) {
			Papel papel = (Papel) value;
			retorno = papel.getDescricao();
		}
		
		return retorno;
	}

}
